# -*- coding: utf-8 -*-
# @author okumura@laurus.co.jp

from gaeo.controller import BaseController
from libs.laurus.action import before_action
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import db
from model.hatomo import Hatomo
from model.pigeon import Pigeon
from model.pigeonto import Pigeonto
from datetime import datetime

#データストアへの登録処理(トランザクション)
def insert_pigeon(list, params):
    pigeon = params.get('pigeon')

    pigeon.subject = params.get('subject')
    pigeon.body = params.get('body')
    pigeon.importance = params.get('importance')
    if params.get('send_info') == '1':
        pigeon.send_info = True
    else:
        pigeon.send_info = False
    if params.get('read_info') == '1':
        pigeon.read_info = True
    else:
        pigeon.read_info = False
    if params.get('create_from'):
        pigeon.create_from = params.get('create_from')
    if params.get('draft') == '1':
        pigeon.status = 'Draft'
    else:
        pigeon.status = 'Sent'
    pigeon.post_at = datetime.now()
    pigeon.put()

    #宛先(Pigeonto)を登録
    if params.get('to') != '':
        for to in params.get('to_users'):
            pigeonto = Pigeonto(parent=pigeon,pigeon=pigeon,to_user=to,status=pigeon.status)
            pigeonto.put()
    

class NewController(BaseController):
    def before_action(self):
        before_action(self)
        self.importances = Pigeon.importances

    #入力フォームアクション
    @login_required
    def index(self):
        self.pigeon = {}
        if self.params.get('id'):
            pigeon = Pigeon.get_by_id(int(self.params.get('id')))
            if pigeon:
                if pigeon.from_user != self.user:
                    #from_userがcurrent_userでないならTOPへリダイレクト
                    self.redirect('/')
                    return
                if pigeon.status != 'Draft':
                    #状態が下書きでない場合はリダイレクト
                    self.redirect('/')
                    return
                self.pigeon['id'] = self.params.get('id')
                for prop in Pigeon.properties():
                    self.pigeon[prop] = getattr(pigeon, prop)
                pigeontos = []
                for to in pigeon.pigeontos:
                    pigeontos.append(to.to_user.email())
                self.pigeon['to'] = ','.join(pigeontos)
            else:
                #伝書鳩が取得できなかったのでリダイレクト
                self.redirect('/')
                return

        if self.pigeon == {}:
            #デフォルト値を登録
            self.pigeon['importance'] = 'Normal'
            self.pigeon['send_info'] = True

    #登録(送信)処理アクション
    def post(self):
        #ログインしていなければTOPへリダイレクト(アノテーションが使えない)
        if not self.user:
            self.redirect('/')
            return

        #ハトモに登録していなければ自動で登録する
        if not Hatomo.get_by_key_name(self.user.email()):
            hatomo = Hatomo(key_name=self.user.email(),user=self.user,email=self.user.email())
            hatomo.put()

        #入力バリデートの開始
        errors = {}
        if self.params.get('draft') != '1':
            if self.params.get('subject') == '':
                errors['subject'] = u'件名を入力して下さい'
            else:
                if len(self.params.get('subject')) > 500:
                    errors['subject'] = u'件名が長過ぎます'

            if self.params.get('body') == '':
                errors['body'] = u'本文を入力して下さい'

            if self.params.get('to') == '':
                errors['to'] = u'宛先を入力して下さい'

        #importanceのバリデート
        if not self.params.get('importance') in dict(Pigeon.importances).keys():
            errors['importance'] = u'不正な重要度'

        #toをコンマで分割してバリデート
        if self.params.get('to') != '':
            self.params['to_users'] = []
            error_users = []
            for to in self.params.get('to').split(','):
                email = to.strip()
                if Hatomo.get_by_key_name(email):
                    self.params.get('to_users').append(users.User(email))
                else:
                    error_users.append(email)
            if len(error_users) > 0:
                errors['to'] = u'[%s]はハトモに登録されていません' % '],['.join(error_users)

        if self.params.get('id') != '':
            self.params['pigeon'] = Pigeon.get_by_id(int(self.params.get('id')))
            if self.params.get('pigeon'):
                if self.params.get('pigeon').from_user != self.user:
                    #from_userがcurrent_userでないならTOPへリダイレクト
                    self.redirect('/')
                    return
            else:
                #存在しないidを指定したのでTOPへリダイレクト
                self.redirect('/')
                return
        else:
            #新規作成
            self.params['pigeon'] = Pigeon(from_user=self.user)

        #作成元をインスタンス化
        if self.params.get('create_from') != '':
            self.params['create_from'] = Pigeon.get_by_id(int(self.params.get('create_from')))

        #入力エラーがあれば入力フォームを表示して終了
        if len(errors) > 0:
            self.errors = errors
            self.pigeon = {}
            for prop in Pigeon.properties():
                self.pigeon[prop] = self.params.get(prop)
            self.pigeon['id'] = self.params.get('id')
            self.pigeon['to'] = self.params.get('to')
            self.render(template='index')
            return

        #DBへ登録
        try:
            #宛先の削除(トランザクション内では実行できない)
            # @todo ここでエラーになった場合の処理を考える
            if self.params.get('id') != '':
                for to in self.params.get('pigeon').pigeontos:
                    to.delete()

            #トランザクション開始
            db.run_in_transaction(insert_pigeon, [], self.params)
        except:
            #登録失敗
            self.errors = {'other': u'登録に失敗しました'}
            self.pigeon = {}
            for prop in Pigeon.properties():
                self.pigeon[prop] = self.params.get(prop)
            self.pigeon['id'] = self.params.get('id')
            self.pigeon['to'] = self.params.get('to')
            self.render(template='index')
            return

        if self.params.get('draft') == '1':
            #下書きへリダイレクトする
            self.session['message'] = u'登録しました'
            self.session.put()
            self.redirect('/draft')
            return
        else:
            #通知メールの送信
            if self.params.get('send_info') == '1':
                for to in self.params.get('to_users'):
                    mail.send_mail(
                        self.user.email(),
                        to.email(),
                        u'[伝書鳩]%s' % self.params.get('subject'),
                        """
伝書鳩送信通知
%s
""" % 'https://pigeon-laurus.appspot.com/inbox'
                    )
            #送信済みへリダイレクトする
            self.session['message'] = u'送信しました'
            self.session.put()
            self.redirect('/sent')
            return

    #返信処理アクション
    def reply(self):
        create_from = Pigeon.get_by_id(int(self.params.get('create_from')))
        #作成元が取得できなければリダイレクト
        if not create_from:
            self.redirect('/')
            return
        #宛先にcurrent_userが含まれていなければリダイレクト
        user_check = False
        for to in create_from.pigeontos:
            if to.to_user == self.user:
                user_check = True
                break
        if not user_check:
            self.redirect('/')
            return

        self.pigeon = {}
        self.pigeon['create_from'] = create_from
        self.pigeon['importance'] = 'Normal'
        self.pigeon['send_info'] = True
        self.pigeon['subject'] = u'Re: %s' % create_from.subject
        body = []
        for row in create_from.body.split("\n"):
            body.append(u'> %s' % row)
        self.pigeon['body'] = u"\n\n%s" % "\n".join(body)
        self.pigeon['to'] = create_from.from_user.email()
        self.render(template='index')

    #転送処理アクション
    def forward(self):
        create_from = Pigeon.get_by_id(int(self.params.get('create_from')))
        #作成元が取得できなければリダイレクト
        if not create_from:
            self.redirect('/')
            return
        #宛先にcurrent_userが含まれていなければリダイレクト
        user_check = False
        for to in create_from.pigeontos:
            if to.to_user == self.user:
                user_check = True
                break
        if not user_check:
            self.redirect('/')
            return

        self.pigeon = {}
        self.pigeon['create_from'] = create_from
        self.pigeon['importance'] = create_from.importance
        self.pigeon['send_info'] = True
        self.pigeon['subject'] = u'Fw: %s' % create_from.subject
        body = []
        body.append(u'%s %s<%s>:' % (
            create_from.post_at,
            create_from.from_user.nickname(),
            create_from.from_user.email()
        ))
        for row in create_from.body.split("\n"):
            body.append(u'> %s' % row)
        self.pigeon['body'] = u"\n\n%s" % "\n".join(body)
        self.render(template='index')

    #再送処理アクション
    def resend(self):
        create_from = Pigeon.get_by_id(int(self.params.get('create_from')))
        #作成元が取得できなければリダイレクト
        if not create_from:
            self.redirect('/')
            return
        #送信元がcurrent_userでなければリダイレクト
        if create_from.from_user != self.user:
            self.redirect('/')
            return

        self.pigeon = {}
        self.pigeon['create_from'] = create_from
        self.pigeon['importance'] = create_from.importance
        self.pigeon['send_info'] = create_from.send_info
        self.pigeon['read_info'] = create_from.read_info
        self.pigeon['subject'] = create_from.subject
        self.pigeon['body'] = create_from.body
        pigeontos = []
        for to in create_from.pigeontos:
            pigeontos.append(to.to_user.email())
        self.pigeon['to'] = ','.join(pigeontos)
        self.render(template='index')
        return

